package com.stedu.controller;

import cn.hutool.captcha.LineCaptcha;
import com.stedu.bean.Admin;
import com.stedu.bean.RespBean;
import com.stedu.exception.SteduException;
import com.stedu.service.AdminService;
import com.stedu.utils.JwtUtils;
import com.stedu.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@CrossOrigin
@RestController
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/login")
    public RespBean login(@Validated String username, String password, String captchaId, String captcha) throws SteduException {
        /*
         判断验证码  -- 和Redis中保存的验证码文本相比
        */
        String captchaRedis = (String) redisUtil.get(captchaId);
        if (captchaRedis == null || (captchaRedis != null && !captchaRedis.equalsIgnoreCase(captcha))) {
            return RespBean.error("验证码错误，请重试");
        }
        //判断用户名和密码是否正确
        Admin admin = adminService.login(username, password);
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", admin.getId());
        map.put("username", admin.getUsername());
        map.put("permissions", 1);
        String jwt = JwtUtils.generateJwt(map);
        return RespBean.ok("登陆成功", jwt);
    }

    //@GetMapping("/logout")
    //public RespBean logout(HttpSession session) {
    //    //获取session,让session失效
    //    session.invalidate();
    //    //返回注销成功的消息
    //    return RespBean.ok("退出成功");
    //
    //}

    @GetMapping("/captcha")
    public RespBean captcha() throws IOException {
        //生成验证码对象
        LineCaptcha captcha = new LineCaptcha(120, 38, 4, 20);
        //获取验证码的文本
        String code = captcha.getCode();
        //生成唯一的ID
        String captchaId = UUID.randomUUID().toString().replace("-", "");
        //获取验证码文本保存到redis中
        redisUtil.set(captchaId, code, 100);
        //图片进行Base64-->字符串
        String captchaImageBase64Data = captcha.getImageBase64Data();
        //将captchaId和验证码图片发给浏览器
        HashMap<String, Object> map = new HashMap<>();
        map.put("captchaId", captchaId);
        map.put("captchaImageBase64Data", captchaImageBase64Data);
        return RespBean.ok("", map);
    }
}
